<template>
  <!-- TEST src/pages/channel/list/component/FormDialog -->
  <t-dialog v-model:visible="model" :header="dialogTitle" :confirm-loading="confirmPending" confirm-btn="确定" @confirm="handleConfirm">
    <t-form ref="dialogForm" :rules="rules" :data="formData">
      <slot v-bind="{ formData }" />
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts" generic="T extends Data">
// TEST src/pages/channel/list/component/FormDialog
import type { Data, FormInstanceFunctions, FormRules } from 'tdesign-vue-next'
import { MessagePlugin } from 'tdesign-vue-next'
import { computed, reactive, ref, useTemplateRef } from 'vue'

const props = defineProps<{ id?: string, data: T, rules?: FormRules<T>, name: string, create: (data: T) => void | Promise<void>, update: (id: string, data: T) => void | Promise<void> }>()
const emits = defineEmits<{ (e: 'success'): void }>()
const model = defineModel('visible', { type: Boolean })
const formData = reactive<T>(props.data)
const isEditMode = computed(() => !!props.id)
const dialogTitle = computed(() => (isEditMode.value ? `编辑${props.name}` : `添加${props.name}`))
const dialogForm = useTemplateRef<FormInstanceFunctions<T>>('dialogForm')
const confirmPending = ref(false)
function handleConfirm() {
  dialogForm.value?.validate().then((validateResult) => {
    if (validateResult === true) {
      confirmPending.value = true
      if (isEditMode.value) {
        const res = props.update(props.id!, { ...formData } as T)
        if (res instanceof Promise) {
          res.then(() => {
            confirmPending.value = false
            model.value = false
            MessagePlugin.success('更新成功')
            emits('success')
          })
        }
        else {
          confirmPending.value = false
          model.value = false
          MessagePlugin.success('更新成功')
          emits('success')
        }
      }
      else {
        const res = props.create({ ...formData } as T)
        if (res instanceof Promise) {
          res.then(() => {
            confirmPending.value = false
            model.value = false
            MessagePlugin.success('创建成功')
            emits('success')
          })
        }
        else {
          confirmPending.value = false
          model.value = false
          MessagePlugin.success('创建成功')
          emits('success')
        }
      }
    }
  })
}
</script>
<style scoped>

</style>
